package com.school.sports.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.school.sports.entity.SysDictType;
import com.school.sports.service.SysDictTypeService;
import com.school.sports.common.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * 字典类型管理控制器
 * 提供字典类型的CRUD操作、缓存刷新等功能
 */
@RestController
@RequestMapping("/api/dict-type")
public class SysDictTypeController {

    private static final Logger logger = LoggerFactory.getLogger(SysDictTypeController.class);

    @Autowired
    private SysDictTypeService sysDictTypeService;

    /**
     * 分页查询字典类型列表
     * @param currentPage 当前页码
     * @param pageSize 每页大小
     * @param sysDictType 查询条件
     * @return 分页结果
     */
    @GetMapping("/page/{currentPage}/{pageSize}")
    @PreAuthorize("hasRole('管理员')")
    public Result<IPage<SysDictType>> getDictTypePage(
            @PathVariable("currentPage") Integer currentPage,
            @PathVariable("pageSize") Integer pageSize,
            SysDictType sysDictType) {

        logger.info("分页查询字典类型列表，当前页码：{}，每页条数：{}，查询条件：{}", currentPage, pageSize, sysDictType);

        // 参数校验
        if (currentPage == null || currentPage <= 0) {
            currentPage = 1;
        }
        if (pageSize == null || pageSize <= 0) {
            pageSize = 10;
        }

        try {
            IPage<SysDictType> page = sysDictTypeService.getDictTypePage(currentPage, pageSize, sysDictType);
            logger.info("查询字典类型列表成功，共{}条记录", page.getTotal());
            return Result.success(page);
        } catch (Exception e) {
            logger.error("查询字典类型列表异常：{}", e.getMessage(), e);
            return Result.fail("查询失败：" + e.getMessage());
        }
    }

    /**
     * 根据ID查询字典类型详情
     * @param dictTypeId 字典类型ID
     * @return 字典类型详情
     */
    @GetMapping("/{dictTypeId}")
    @PreAuthorize("hasRole('管理员')")
    public Result<SysDictType> getDictTypeById(@PathVariable("dictTypeId") Long dictTypeId) {
        logger.info("查询字典类型详情，字典类型ID：{}", dictTypeId);

        if (dictTypeId == null || dictTypeId <= 0) {
            return Result.fail("字典类型ID无效");
        }

        try {
            SysDictType dictType = sysDictTypeService.getById(dictTypeId);
            if (dictType == null) {
                return Result.fail("字典类型不存在");
            }
            logger.info("查询字典类型详情成功，字典类型：{}", dictType.getDictType());
            return Result.success(dictType);
        } catch (Exception e) {
            logger.error("查询字典类型详情异常：{}", e.getMessage(), e);
            return Result.fail("查询失败：" + e.getMessage());
        }
    }

    /**
     * 根据字典类型获取字典类型信息
     * @param dictType 字典类型
     * @return 字典类型信息
     */
    @GetMapping("/type/{dictType}")
    @PreAuthorize("hasAnyRole('管理员', '老师', '学生', '裁判')")
    public Result<SysDictType> getDictTypeByType(@PathVariable("dictType") String dictType) {
        logger.info("根据字典类型获取字典类型信息：{}", dictType);

        if (dictType == null || dictType.trim().isEmpty()) {
            return Result.fail("字典类型不能为空");
        }

        try {
            SysDictType dictTypeInfo = sysDictTypeService.getDictTypeByType(dictType);
            if (dictTypeInfo == null) {
                return Result.fail("字典类型不存在或已停用");
            }
            logger.info("获取字典类型信息成功：{}", dictType);
            return Result.success(dictTypeInfo);
        } catch (Exception e) {
            logger.error("获取字典类型信息异常：{}", e.getMessage(), e);
            return Result.fail("获取失败：" + e.getMessage());
        }
    }

    /**
     * 获取所有启用的字典类型
     * @return 字典类型列表
     */
    @GetMapping("/all-enabled")
    @PreAuthorize("hasAnyRole('管理员', '老师', '学生', '裁判')")
    public Result<List<SysDictType>> getAllEnabledDictTypes() {
        logger.info("获取所有启用的字典类型");

        try {
            List<SysDictType> dictTypes = sysDictTypeService.getAllEnabledDictTypes();
            logger.info("获取所有启用的字典类型成功，共{}个字典类型", dictTypes.size());
            return Result.success(dictTypes);
        } catch (Exception e) {
            logger.error("获取所有启用的字典类型异常：{}", e.getMessage(), e);
            return Result.fail("获取失败：" + e.getMessage());
        }
    }

    /**
     * 根据名称模糊查询字典类型
     * @param dictName 字典名称
     * @return 字典类型列表
     */
    @GetMapping("/search")
    @PreAuthorize("hasRole('管理员')")
    public Result<List<SysDictType>> getDictTypesByName(@RequestParam("dictName") String dictName) {
        logger.info("根据名称模糊查询字典类型：{}", dictName);

        if (dictName == null || dictName.trim().isEmpty()) {
            return Result.fail("字典名称不能为空");
        }

        try {
            List<SysDictType> dictTypes = sysDictTypeService.getDictTypesByName(dictName);
            logger.info("根据名称模糊查询字典类型成功，共{}个结果", dictTypes.size());
            return Result.success(dictTypes);
        } catch (Exception e) {
            logger.error("根据名称模糊查询字典类型异常：{}", e.getMessage(), e);
            return Result.fail("查询失败：" + e.getMessage());
        }
    }

    /**
     * 新增字典类型
     * @param sysDictType 字典类型信息
     * @return 操作结果
     */
    @PostMapping
    @PreAuthorize("hasRole('管理员')")
    public Result<String> addDictType(@Valid @RequestBody SysDictType sysDictType) {
        logger.info("新增字典类型：{}", sysDictType.getDictType());

        try {
            // 参数校验
            if (sysDictType.getDictType() == null || sysDictType.getDictType().trim().isEmpty()) {
                return Result.fail("字典类型不能为空");
            }
            if (sysDictType.getDictName() == null || sysDictType.getDictName().trim().isEmpty()) {
                return Result.fail("字典名称不能为空");
            }

            // 获取当前用户ID
            Long currentUserId = getCurrentUserId();

            boolean success = sysDictTypeService.addDictType(sysDictType, currentUserId);
            if (success) {
                logger.info("新增字典类型成功：{}", sysDictType.getDictType());
                return Result.success("添加成功");
            } else {
                return Result.fail("添加失败，字典类型可能已存在");
            }
        } catch (Exception e) {
            logger.error("新增字典类型异常：{}", e.getMessage(), e);
            return Result.fail("添加失败：" + e.getMessage());
        }
    }

    /**
     * 更新字典类型
     * @param sysDictType 字典类型信息
     * @return 操作结果
     */
    @PutMapping
    @PreAuthorize("hasRole('管理员')")
    public Result<String> updateDictType(@Valid @RequestBody SysDictType sysDictType) {
        logger.info("更新字典类型：{}", sysDictType.getId());

        if (sysDictType.getId() == null || sysDictType.getId() <= 0) {
            return Result.fail("字典类型ID无效");
        }

        try {
            // 获取当前用户ID
            Long currentUserId = getCurrentUserId();

            boolean success = sysDictTypeService.updateDictType(sysDictType, currentUserId);
            if (success) {
                logger.info("更新字典类型成功：{}", sysDictType.getId());
                return Result.success("更新成功");
            } else {
                return Result.fail("更新失败，字典类型不存在或字典类型编码已存在");
            }
        } catch (Exception e) {
            logger.error("更新字典类型异常：{}", e.getMessage(), e);
            return Result.fail("更新失败：" + e.getMessage());
        }
    }

    /**
     * 删除字典类型
     * @param dictTypeId 字典类型ID
     * @return 操作结果
     */
    @DeleteMapping("/{dictTypeId}")
    @PreAuthorize("hasRole('管理员')")
    public Result<String> deleteDictType(@PathVariable("dictTypeId") Long dictTypeId) {
        logger.info("删除字典类型：{}", dictTypeId);

        if (dictTypeId == null || dictTypeId <= 0) {
            return Result.fail("字典类型ID无效");
        }

        try {
            boolean success = sysDictTypeService.deleteDictType(dictTypeId);
            if (success) {
                logger.info("删除字典类型成功：{}", dictTypeId);
                return Result.success("删除成功");
            } else {
                return Result.fail("删除失败，字典类型不存在或存在关联数据");
            }
        } catch (Exception e) {
            logger.error("删除字典类型异常：{}", e.getMessage(), e);
            return Result.fail("删除失败：" + e.getMessage());
        }
    }

    /**
     * 批量删除字典类型
     * @param dictTypeIds 字典类型ID列表
     * @return 操作结果
     */
    @DeleteMapping("/batch")
    @PreAuthorize("hasRole('管理员')")
    public Result<String> batchDeleteDictTypes(@RequestBody List<Long> dictTypeIds) {
        logger.info("批量删除字典类型：{}", dictTypeIds);

        if (dictTypeIds == null || dictTypeIds.isEmpty()) {
            return Result.fail("请选择要删除的字典类型");
        }

        try {
            boolean success = sysDictTypeService.batchDeleteDictTypes(dictTypeIds);
            if (success) {
                logger.info("批量删除字典类型成功，共{}个字典类型", dictTypeIds.size());
                return Result.success("批量删除成功");
            } else {
                return Result.fail("批量删除失败，可能存在关联数据");
            }
        } catch (Exception e) {
            logger.error("批量删除字典类型异常：{}", e.getMessage(), e);
            return Result.fail("批量删除失败：" + e.getMessage());
        }
    }

    /**
     * 修改字典类型状态
     * @param dictTypeId 字典类型ID
     * @param status 状态
     * @return 操作结果
     */
    @PutMapping("/{dictTypeId}/status")
    @PreAuthorize("hasRole('管理员')")
    public Result<String> updateDictTypeStatus(
            @PathVariable("dictTypeId") Long dictTypeId,
            @RequestParam("status") Integer status) {

        logger.info("修改字典类型状态：{} -> {}", dictTypeId, status);

        if (dictTypeId == null || dictTypeId <= 0) {
            return Result.fail("字典类型ID无效");
        }

        if (status == null || (status != 0 && status != 1)) {
            return Result.fail("状态值无效");
        }

        try {
            Long currentUserId = getCurrentUserId();
            boolean success = sysDictTypeService.updateDictTypeStatus(dictTypeId, status, currentUserId);
            if (success) {
                logger.info("修改字典类型状态成功：{}", dictTypeId);
                return Result.success("状态修改成功");
            } else {
                return Result.fail("状态修改失败");
            }
        } catch (Exception e) {
            logger.error("修改字典类型状态异常：{}", e.getMessage(), e);
            return Result.fail("状态修改失败：" + e.getMessage());
        }
    }

    /**
     * 刷新字典缓存
     * @return 操作结果
     */
    @PostMapping("/refresh-cache")
    @PreAuthorize("hasRole('管理员')")
    public Result<String> refreshDictCache() {
        logger.info("刷新字典缓存");

        try {
            boolean success = sysDictTypeService.refreshDictCache();
            if (success) {
                logger.info("刷新字典缓存成功");
                return Result.success("缓存刷新成功");
            } else {
                return Result.fail("缓存刷新失败");
            }
        } catch (Exception e) {
            logger.error("刷新字典缓存异常：{}", e.getMessage(), e);
            return Result.fail("缓存刷新失败：" + e.getMessage());
        }
    }

    /**
     * 检查字典类型是否存在
     * @param dictType 字典类型
     * @param excludeId 排除的ID
     * @return 检查结果
     */
    @GetMapping("/check-type")
    @PreAuthorize("hasRole('管理员')")
    public Result<Boolean> checkDictTypeExists(
            @RequestParam("dictType") String dictType,
            @RequestParam(value = "excludeId", required = false) Long excludeId) {

        logger.info("检查字典类型是否存在：{}，排除ID：{}", dictType, excludeId);

        if (dictType == null || dictType.trim().isEmpty()) {
            return Result.fail("字典类型不能为空");
        }

        try {
            boolean exists = sysDictTypeService.checkDictTypeExists(dictType, excludeId);
            logger.info("检查字典类型是否存在完成：{} -> {}", dictType, exists);
            return Result.success(exists);
        } catch (Exception e) {
            logger.error("检查字典类型是否存在异常：{}", e.getMessage(), e);
            return Result.fail("检查失败：" + e.getMessage());
        }
    }

    /**
     * 获取当前用户ID
     * 这里简化处理，实际应该从Spring Security上下文中获取
     * @return 用户ID
     */
    private Long getCurrentUserId() {
        // TODO: 从Spring Security上下文中获取当前用户ID
        return 1L; // 临时返回固定值
    }
}